'use strict';

const { formatUser } = require('../utils/formatUser');
const { doCrypto } = require('../utils/cryp');
const { ErrorModel, SuccessModel } = require('../utils/ResModel');
const { loginFailInfo, deleteUserFailInfo } = require('../utils/ErrorModel');

module.exports = app => {
  class UserService extends app.Service {

    // 获取用户信息
    async getUserInfo({ userName, password }) {
      const whereOpt = {
        userName,
      };

      if (password || password === '') {
        // 对象做拼接
        Object.assign(whereOpt, { password: doCrypto(password) });
      }

      // 查询
      const result = await app.model.User.findOne({
        attributes: [ 'id', 'userName', 'nickName', 'avatar', 'city' ],
        where: whereOpt,
      });
      // 返回统一的数据格式
      return formatUser(result);

    }

    // 添加用户
    async createUser({ userName, password, gender = 3, nickName }) {
      const result = this.app.model.User.create({
        userName,
        password: doCrypto(password),
        gender,
        nickName: nickName ? nickName : userName,
      });

      return result;
    }

    // doLogin
    async doLogin({ userName, password }) {

      const userInfo = await this.getUserInfo({ userName, password });
      // 登录失败
      if (!userInfo) {
        // 返回登录错误信息
        return new ErrorModel(loginFailInfo);
      }

      // 成功，设置session
      if (!this.ctx.session.userInfo) {
        this.ctx.session.userInfo = userInfo;
      }
      return new SuccessModel();
    }

    // 删除
    async deleteCurrentUser(userName) {
      const result = await this.app.model.User.destroy({
        where: {
          userName,
        },
      });

      if (result > 0) {
        // 成功;
        return new SuccessModel();
      }
      // 失败
      return new ErrorModel(deleteUserFailInfo);
    }

  }
  return UserService;
};
